import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

public class Cart implements Serializable {
    private Integer userId;
    private Map<Integer, Integer> items;

    public Cart() {
        this.items = new HashMap<>();
    }

    public Cart(Integer userId, Map<Integer, Integer> items) {
        this.userId = userId;
        this.items = items != null ? items : new HashMap<>();
    }

    public Integer getUserId() { return userId; }
    public void setUserId(Integer userId) { this.userId = userId; }

    public Map<Integer, Integer> getItems() { return items; }
    public void setItems(Map<Integer, Integer> items) { this.items = items; }

    public void addItem(Integer productId, Integer quantity) {
        items.merge(productId, quantity, Integer::sum);
    }

    public void clear() {
        items.clear();
    }

    public boolean isEmpty() {
        return items.isEmpty();
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("购物车内容:\n");
        if (items.isEmpty()) {
            sb.append("  购物车为空\n");
        } else {
            for (Map.Entry<Integer, Integer> entry : items.entrySet()) {
                sb.append(String.format("  商品ID: %d, 数量: %d\n", entry.getKey(), entry.getValue()));
            }
        }
        return sb.toString();
    }
}